<?php

/**
 * @version     $Id: AdminsafeNotifier.php 3 2010-10-08 17:49:35Z obalyuk87@gmail.com $
 * @package     AdminSafe
 * @subpackage  Components
 * @copyright   Copyright (C) 2010 Oleksandr Balyuk (www.boolcast.com)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL v2
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
// No direct access
defined('_JEXEC') or die('Restricted access');
require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_adminsafe' . DS . 'classes' . DS . 'AdminsafeObject.php';
require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_adminsafe' . DS . 'helpers' . DS . 'AdminsafeUserDetector.php';
jimport('joomla.mail.helper');

/**
 * Description of AdminsafeNotifier
 *
 * @author Oleksandr Balyuk <obalyuk@boolcast.com>
 */
class AdminsafeNotifier extends AdminsafeObject {

    /**
     * Component Parameters
     * @var JParameter
     */
    protected $_params = null;
    /**
     * List of users from the database that need to be notified
     * @var array
     */
    protected $_userList = array();
    /**
     * User's IP Address
     * @var string
     */
    protected $_userIpAddress = null;
    /**
     * User's Operating System
     * @var string
     */
    protected $_userOS = null;
    /**
     * User's Browser
     * @var string
     */
    protected $_userBrowser = null;

    /**
     * Sends notifications to users
     *
     * @return void
     */
    public function sendNotifications() {

        //
        $this->_loadParameters();
        JFactory::getLanguage()->load('com_adminsafe', JPATH_ADMINISTRATOR);

        //  Get list of users to notify (from db and custom)
        $userList = $this->_getUserList();

        //
        if ($userList) {
            //  Scan through the list of user to notify
            foreach ($userList as $user) {
                //  Notify user
                $this->_notifyUser($user->email, $user->name);
            }
        }
    }

    /**
     * Loads components parameters
     */
    protected function _loadParameters() {
        if (!$this->_params) {
            jimport('joomla.application.component.helper');
            $this->_params = JComponentHelper::getParams('com_adminsafe');
        }
    }

    /**
     * Loads list of users that have to be notified
     *
     * @return array
     */
    protected function _getUserList() {

        if (!$this->_userList) {

            //
            //  Database
            //  Get list of GIDs to notify
            $gids = $this->_getGidsToNotify();
            if ($gids) {
                //  Get users from database
                $query = 'SELECT name, email'
                        . ' FROM #__users'
                        . ' WHERE gid  IN (' . implode(',', $gids) . ') '
                        . ' AND sendEmail = 1'
                        . ' GROUP BY email';

                $this->_db->setQuery($query);
                $this->_userList = $this->_db->loadObjectList();
            }


            //
            //  Custom List
            $customEmailList = $this->_params->get('notifyCustom', '');
            $customEmailList = explode(',', $customEmailList);
            if ($customEmailList) {
                //  Scan through the email list
                foreach ($customEmailList as $email) {

                    //  Remove extra spaces from the email address
                    //  When entered in CSV format user might add spaced after comma, need to trim it
                    $email = trim($email);

                    //  Check if email address is correct, this is neccessary because
                    //  the email list is user entered and not validated... emails might not be valid
                    if (JMailHelper::isEmailAddress($email)) {
                        $user = (object) array('email' => $email, 'name' => JText::_('CAS_DEFAULT_RECEIPIENT_NAME'));
                        $this->_userList[] = $user;
                    }
                }
            }
        }

        //  Retrurn User List
        return $this->_userList;
    }

    /**
     * Loads list of GIDs that need to be notified
     *
     * @return array
     */
    protected function _getGidsToNotify() {
        //
        $gids = array();

        //
        if ($this->_params->get('notifySuperAdmin', 1)) {
            $gids[] = UserRoles::SUPER_ADMINISTRATOR;
        }
        //
        if ($this->_params->get('notifyAdmin', 0)) {
            $gids[] = UserRoles::ADMINISTRATOR;
        }
        //
        if ($this->_params->get('notifyManager', 0)) {
            $gids[] = UserRoles::MANAGER;
        }

        //
        return $gids;
    }

    /**
     * Notify User that the account needs to be unlocked
     *
     * @param string $email
     * @param string $name
     */
    protected function _notifyUser($email, $name=null) {

        //
        $mailfrom = $this->_app->getCfg('mailfrom');
        $fromname = $this->_app->getCfg('fromname');
        $sitename = $this->_app->getCfg('sitename');

        //  Subject
        $subject = JText::sprintf('CAS_NOTIFICATION_EMAIL_SUBJECT', $sitename);
        $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');

        //
        // [1] - User Name
        // [2] - Event
        // [3] - Server Time
        // [4] - GMT Time
        // [5] - IP Address
        // [6] - Operating System
        // [7] - Browser
        //
        $args = array();
        $args[1] = $name;
        $args[2] = JText::_('CAS_INVALID_SECRET_WORD');
        $args[3] = JFactory::getDate(time())->toFormat();
        $args[4] = JFactory::getDate()->toFormat();
        $args[5] = $this->_getUserIP();
        $args[6] = $this->_getUserOS();
        $args[7] = $this->_getUserBrowser();

        $message = JText::sprintf('CAS_NOTIFICATION_EMAIL_BODY', $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]);
        if ($this->_params->get('notifyAttachHowTo', 1)) {
            $message .= "\n" . JText::_('CAS_NOTIFICATION_HOW_TO_CHANGE');
        }
        $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');

        //
        return JUtility::sendMail($mailfrom, $fromname, $email, $subject, $message);
    }

    /**
     * Gets user IP Address
     * 
     * @return string
     */
    protected function _getUserIP() {
        // 
        if (!$this->_userIpAddress) {
            //
            $this->_userIpAddress = AdminsafeUserDetector::getIpAddress();
        }

        //
        return $this->_userIpAddress;
    }

    /**
     * Gets user Operating System
     *
     * @return string
     */
    protected function _getUserOS() {
        // 
        if (!$this->_userOS) {
            //
            $this->_userOS = AdminsafeUserDetector::getOs();
        }

        //
        return $this->_userOS;
    }

    /**
     * Gets user Browser
     *
     * @return string
     */
    protected function _getUserBrowser() {
        //
        if (!$this->_userBrowser) {
            //
            $this->_userBrowser = AdminsafeUserDetector::getBrowser();
        }

        //
        return $this->_userBrowser;
    }

}